import { defineStore } from "pinia";
const setLocalCart = (cartList) => {
  if (typeof cartList === "object" && cartList !== null) {
    const cartListString = JSON.stringify(cartList);
    localStorage.setItem("cartList", cartListString);
  } else {
    console.error("Attempted to store non-object as cartList:", cartList);
  }
};
//缓存
const getLoacalCartList = () => {
  // try {
  //   const cartListString = localStorage.getItem("cartList");
  //   return cartListString ? JSON.parse(cartListString) : {};
  // } catch (error) {
  //   console.error("Error parsing cartList from localStorage:", error);
  //   return {};
  // }
  return JSON.parse(localStorage.getItem("cartList")) || {};
};
export const useCartStore = defineStore("cart", {
  actions: {
    // 加入购物车
    changeItemToCart(shopId, productId, productInfo, num) {
      let shopInfo = this.cartList[shopId];
      if (!shopInfo) {
        shopInfo = {};
      }
      let product = shopInfo[productId];
      if (!product) {
        // 创建新产品并数量为0
        product = { ...productInfo, count: 0 };
      }
      product.count = Math.max(0, product.count + num);
      if (num > 0) {
        product.check = true;
      }
      shopInfo[productId] = product;
      if (product.count == 0) {
        delete shopInfo[productId];
      }
      this.cartList[shopId] = shopInfo;
      setLocalCart(this.cartList);
    },
    // 购物车中商品选择
    changeChecked(shopId, productId) {
      const product = this.cartList[shopId][productId];
      product.check = !product.check;
      setLocalCart(this.cartList);
    },
    // 清空购物车
    clearCart(shopId) {
      this.cartList[shopId] = {};
      setLocalCart(this.cartList);
    },

    allCart(shopId) {
      const products = this.cartList[shopId];
      this.Allcheck = !this.Allcheck
      for (const key in products) {
        const product = products[key];
        // 点击全选就全选
        product.check = this.Allcheck;
      }
      setLocalCart(this.cartList);
    },
    
  },
  state() {
    return {
      cartList: getLoacalCartList(),
      Allcheck: false
    };
  },
  getters: {},
});

export const useShopStore = defineStore("shop", {
  actions: {},
  state() {
    return {
      shops: {},
    };
  },
});
export const usePerson = defineStore("person", {
  state() {
    return {
      username: "12345678910",
      nickname: "一位代码爱好者",
    };
  },
  actions: {
    edit(newusername, newnickname) {
      this.username = newusername;
      this.nickname = newnickname;
    },
  },
});
